package com.yjd.comm.user.interceptor;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.yjd.comm.system.model.SysParamModel;
import com.yjd.comm.system.util.SysParamUtil;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.util.StringUtil;
import com.yjd.comm.util.TxtFileCacheUtil;
import com.yjd.comm.vo.Constant.SysParamKeyEnum;

/**
 * <b>description</b>：允许的功能访问拦截器 <br>
 * <b>time</b>：2014-11-15下午12:39:48 <br>
 * <b>author</b>： ready likun_557@163.com
 */
public class AllowFeatureListInterceptor extends HandlerInterceptorAdapter {

	private static Logger logger = Logger
			.getLogger(AllowFeatureListInterceptor.class);
	private static String ALLOWFEATURELIST = "allowfeaturelist.txt";

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// 判断有没有在拦截排除列表中
		if (isAccessIp(request) || !urlIsNeedValidate(request)) {
			return super.preHandle(request, response, handler);
		}
		return false;
	}

	private String getRequestUrl(HttpServletRequest request) {
		return request.getRequestURI();
	}

	/**
	 * 判断是否是不需要验证的ip
	 * 
	 * @param request
	 * @return
	 */
	private boolean isAccessIp(HttpServletRequest request) {
		String ip = ServletUtil.getIpAddr(request);
		logger.info("ip:" + ip);
		try {
			SysParamModel sp = SysParamUtil
					.getSysParamModel(SysParamKeyEnum.ALLOW_ACCESS_IP_LIST);
			if (sp != null && StringUtil.isNotEmpty(sp.getParam_value())
					&& StringUtil.isNotEmpty(ip)) {
				String[] ips = sp.getParam_value().split(";");
				for (String string : ips) {
					if (ip.equals(string) || ip.startsWith(string)) {
						return true;
					}
				}
			}
		} catch (Exception e) {
			logger.error("获取[SysParamKeyEnum.ALLOW_ACCESS_IP_LIST]参数出错:"
					+ e.getMessage());
		}
		return false;
	}

	/**
	 * @Title: urlIsNeedValidate
	 * @Description: 判断url是否需要验证
	 * @param @param requestUrl
	 * @param @return 设定文件
	 * @return boolean 返回类型
	 * @throws
	 */
	private boolean urlIsNeedValidate(HttpServletRequest request) {
		String requestUrl = getRequestUrl(request);
		String contextPath = request.getContextPath();
		if (requestUrl.startsWith(contextPath)) {
			requestUrl = requestUrl.substring(contextPath.length());
		}
		List<String> list = TxtFileCacheUtil.get(ALLOWFEATURELIST);
		if (list != null) {
			for (String string : list) {
				Pattern pattern = Pattern.compile(string);
				Matcher matcher = pattern.matcher(requestUrl);
				boolean b = matcher.matches();
				if (b) {
					return false;
				}
			}
		}
		return true;
	}

}
